package Q5;


import java.io.File;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;

public class ClientRecieveThread extends Thread {
    private Socket socket;

    public ClientRecieveThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        ObjectInputStream objectInputStream = null;
        try {
            while (true) {
                objectInputStream = new ObjectInputStream(socket.getInputStream());
                Message msg = (Message) objectInputStream.readObject();
                System.out.println("客户端收到消息");
                if ("chat".equals(msg.getMessageType())) {
                    System.out.println(msg.getUser() + "说" + msg.getData());
                } else if ("file".equals(msg.getMessageType())) {
                    System.out.println("客户端收到文件");
                    File dict = new File("./code/ClientRecieved/");
                    if (!dict.isDirectory()) {
                        dict.mkdir();
                    }
                    do {
                        msg = Util.SocketMessagetoFile(objectInputStream, msg, dict.getPath());
                    }
                    while (null != msg);
                    System.out.println("传输成功");
                }
            }
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                assert objectInputStream != null;
                objectInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
